import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addItemAction, changeInputValue, deleteItem } from './store/actionCreators';



// ui组件
const TodoList = (props) => {
    const {inputValue, handleChangeInput, handleBtnClick, handleDeleteClick, list} = props;
    return (
        <div>
            <div>
                <input value={inputValue}
                       onChange={handleChangeInput}
                />
                <button onClick={handleBtnClick}>提交</button>
            </div>
            <ul>
                {
                    list.map((item, index) => {
                        return <li
                            onClick={() => handleDeleteClick(index)}
                            key={index}>{item}</li>
                    })
                }
            </ul>
        </div>
    )
}

//class TodoList extends Component {
//    render() {
//        return (
//            <div>
//                <div>
//                    <input value={this.props.inputValue}
//                           onChange={this.props.handleChangeInput}
//                    />
//                    <button onClick={this.props.handleBtnClick}>提交</button>
//                </div>
//                <ul>
//                    {
//                        this.props.list.map((item, index) => {
//                            return <li
//                                onClick={() => this.props.handleDeleteClick(index)}
//                                key={index}>{item}</li>
//                        })
//                    }
//                </ul>
//            </div>
//        );
//    }
//}

// 将state映射到props
const mapStateToProps = (state) => {
    return {
        inputValue: state.inputValue,
        list: state.list
    }
}

// store.dispatch 映射到 props
const mapDispatchToProps = (dispatch) => {
    return {
        handleChangeInput (e) {
            const action = changeInputValue(e.target.value);
            dispatch(action);
        },
        handleBtnClick () {
            const action = addItemAction();
            dispatch(action);
        },
        handleDeleteClick (index) {
            const action = deleteItem(index);
            dispatch(action);
        }
    }
}

// 通过connect和store连接     返回容器组件
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);